package com.main.service;

import java.util.ArrayList;
import java.util.List;
import java.util.Random;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;

import com.main.dao.PersonDAO;
import com.main.exception.PersonInventoryDAOException;
import com.main.model.PersonEntity;
import com.main.ui.model.Person;


public class JpaPersonServiceImpl implements PersonService {

	private Logger logger = LoggerFactory.getLogger(JpaPersonServiceImpl.class);
	
	@Autowired
	PersonDAO personDao;
	
	@Override
	@Transactional
	public boolean savePersonDetails(Person person) {
		boolean isPersonSaved = false;
		try{
			if(null == person.getId()){
				Random rand = new Random(3);
				rand.nextInt(100);
				person.setId(Long.valueOf(rand.nextInt(100)));
			}
			personDao.merge(buildPersonEntity(person));
			isPersonSaved = true;
		} catch(PersonInventoryDAOException e){
			logger.error(e.getMessage());
		}
		return isPersonSaved;
	}

	@Override
	public Person getPersonDetails(Long personId) {
		// TODO Auto-generated method stub
		return null;
	}

	@Override
	public List<Person> getAllPersons() {
		List<PersonEntity> persons =  personDao.findAll();
		List<Person> personList = new ArrayList<Person>();
		for(PersonEntity entity : persons) {
			personList.add(buildPerson(entity));
		}
		return personList;
	}
	
	private PersonEntity buildPersonEntity(Person person){
		PersonEntity entity = new PersonEntity();
		entity.setId(person.getId());
		entity.setAge(person.getAge());
		entity.setFirstName(person.getFirstName());
		entity.setLastName(person.getLastName());
		entity.setGender(person.getGender());
		return entity;
	}
	
	private Person buildPerson(PersonEntity person){
		Person entity = new Person();
		entity.setId(person.getId());
		entity.setAge(person.getAge());
		entity.setFirstName(person.getFirstName());
		entity.setLastName(person.getLastName());
		entity.setGender(person.getGender());
		return entity;
	}

	@Override
	public boolean updatePersonDetails(Person person) {
		// TODO Auto-generated method stub
		return false;
	}

	@Override
	public boolean deletePerson(Long personId) {
		// TODO Auto-generated method stub
		return false;
	}
	
}
